<?php
namespace app\admin\controller;


use app\hooks\UserHook;
use think\facade\View;
use think\Model;
use think\Request;

class ModeOrders extends Base
{
    protected $ModelPath = 'ModeOrders';
    protected $model = null;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->con = "ModeOrders";
        $this->title = "模式订单";

        $module = $this->ModelPath;
        $this->model = new \app\admin\model\ModeOrders();

        View::assign(array(
            'module' => $module,
            'title' => $this->title,
            'con' => $this->con,
            'pageSize' => $this->pageSize
        ));
    }

    public function index()
    {
        if(request()->isPost()){
            $params = request()->param();
            $map = [];
//dd($params);
//            $this->model = $this->model
//                ->where('status', 'payed')
//                ->where('is_delete', 0);

            $map[] = ['status', '=', 'payed'];
            $map[] = ['is_delete', '=', 0];
            if(isset($params['id'])){
                if(!empty($params['id'])){
                    $map[] = ['id', '=', $params['id']];
                }
            }

            if(isset($params['user_id'])){
                if(!empty($params['user_id'])){
                    $map[] = ['user_id', '=', $params['user_id']];
                }
            }

            if(isset($params['phone'])){
                if(!empty($params['phone'])){
                    $userId = \app\admin\model\User::where('phone', '=', $params['phone'])->value('id');
//                dd($userId);
//                $this->model = $this->model->where("user_id", $userId);
                    $map[] = ['user_id', '=', $userId];
                }
            }

            if(isset($params['type'])){
                if($params['type'] != 'none'){
                    if($params['type'] == 1){
                        $map[] = ['type', 'in', [1, 2]];
                    }else{
                        $map[] = ['type', '=', $params['type']];
                    }
                }
            }


//            if(isset($params['ship_status'])){
//                $this->model = $this->model->where("ship_status", $params['ship_status']);
//            }

            $total = \app\admin\model\ModeOrders::where($map)//->fetchSql()->select();dd($total);
                ->count();
            $totalAmount = \app\admin\model\ModeOrders::where($map)
                ->sum('pay_amount');


            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $this->model->with(['modeOrdersProduct'])
                 ->where($map)
                // ->where('rec',1)

                ->order('id DESC')
                ->append(['pay_type_format', 'pay_amount_format', 'earnings_format', 'remain_earnings_format'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['totalRow']['pay_amount_format'] = (int)($totalAmount / 100);
            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            $ship_status = request()->param('ship_status', 'pending');
            View::assign(array(
                'ship_status'        =>    $ship_status,
            ));
            return View::fetch();
        }
    }

    public function add(){
        if(request()->isPost()){
            $code = input('code');
            $codeArr = explode(',', $code);
            $sum = $codeArr[0] + $codeArr[1] + $codeArr[2] + $codeArr[3];
            $num = input('num');
            $add = [
                'time'         =>  input('time'),
                'num'     =>  $num,
                'code'     =>  $code,
                'sum'     =>  $sum,
                'status'     =>  1,
            ];

//            var_dump($add);die;

            $this->M->data($add);
            $result = $this->M->save();
            if ($result !== false) {
                (new \app\model\Num())->insert([
                    'name'=>(int)$num + 1,
                    'type'=>1,
                ]);
                $arr['status'] = 1;
                $arr['msg'] = '添加成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '添加失败';
            }
            return $arr;
        }else{
//            $numArr = Db::name('num')
//                ->where('type', 1)
//                ->order('id DESC')->select();
//            View::assign(array(
//                'numArr'        =>    $numArr,
//            ));
            return View::fetch();
        }
    }

    public function edit(){
        if(request()->isPost()){
            $params = request()->param();
//            dd($params);
            $status = $params['status'];
            if($status == 'refund'){
                $update['is_delete'] = 1;
                $update['update_time'] = date('Y-m-d H:i:s');

                $modeOrders = \app\admin\model\ModeOrders::where('id', $params['id'])->find();
                if($modeOrders['type'] == 2 || $modeOrders['type'] == 1){
                    $amount = $modeOrders['principal'];
                    $userId = $modeOrders['user_id'];
                    \app\admin\model\User::where('id', $userId)
                        ->dec('mode_one_spending', (int)$amount)
                        ->update();
                    \app\api\model\User::induce($userId, $amount, 'balance', 'mode_refund');
                    UserHook::run($modeOrders['user_id']);
                }
                if($modeOrders['type'] == 4){
                    $amount = $modeOrders['principal'];
//                    $pid = \app\admin\model\User::where('id', $modeOrders['user_id'])->value('pid');
                    $userId = $modeOrders['user_id'];
                    \app\admin\model\User::where('id', $userId)
                        ->dec('mode_three_spending', (int)$amount)
                        ->update();
                    \app\api\model\User::induce($userId, $amount, 'balance', 'mode_refund');
                    UserHook::run($modeOrders['user_id']);
//                    $this->updateModeThreeAchievement($pid, $amount);
                }
                $save = $this->model->where('id', $params['id'])->update($update);
            }else {
                $save = true;
            }

            if ($save) {
                $arr['status'] = 1;
                $arr['msg'] = '修改成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '修改失败';
            }
            return $arr;
        }else{
            $id = input('id');
            $info = $this->model->where('id', $id)->find();
            View::assign(array(
                'info'        =>    $info,
            ));
            return View::fetch();
        }
    }

//    public function updateModeThreeAchievement($userId, $amount)
//    {
//        if($userId == 0){
//            return true;
//        }else{
//            \app\admin\model\User::where('id', $userId)
//                ->dec('mode_three_performance', (int)$amount)
//                ->dec('mode_three_total', (int)$amount)
//                ->update();
//            $user = \app\admin\model\User::field('pid')->find($userId);
//            $this->updateModeThreeAchievement($user['pid'], $amount);
//        }
//    }
}